package club.janna.rpcdemo.server.register;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class LocalServiceRegister implements ServiceRegister, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Map<String, Object> beanMap = new HashMap<>();

    @Override
    public Object register(String serviceName, Object bean) {
        if(bean == null) {
            String beanName = RPCMapping.getAndDelete(serviceName);
            if (!StringUtils.isEmpty(beanName)) {
                bean = applicationContext.getBean(beanName);
                beanMap.put(serviceName, bean);
            }
        } else {
            beanMap.put(serviceName, bean);
        }
        return bean;
    }

    @Override
    public Object getBean(String serviceName) {
        Object bean = beanMap.get(serviceName);
        // 如果bean不存在，但映射关系在，则从容器中获取，放到beanMap中缓存
        if(bean == null && RPCMapping.exists(serviceName)) {
            bean = register(serviceName, null);
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
